package the.broccoli.weixin.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wisteria.framework.util.HttpUtils;
import the.broccoli.weixin.configuration.WistWeiXinProperties;
import the.broccoli.weixin.service.dto.WXCode2SessionResultDTO;
import the.broccoli.weixin.service.dto.WeiXinAccessTokenDTO;
import the.broccoli.weixin.service.dto.WeiXinLoginReqDTO;
import the.broccoli.weixin.service.dto.WeiXinPhoneNumber;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Service
public class WeiXinService {

    @Resource
    private WistWeiXinProperties wistWeiXinProperties;

    private String appId;
    private String secret;


//    @Resource
//    private WxOpenComponentService wxOpenComponentService;

    public WXCode2SessionResultDTO getLoginCode2Session(WeiXinLoginReqDTO req) {
        initAppConfig(req.getAppType());

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> data = new HashMap<>();
        data.put("appid", this.appId);
        data.put("secret", this.secret);
        data.put("js_code", req.getLoginCode());
        data.put("grant_type", "authorization_code");
        String responseContent = HttpUtils.get(url, null, data);
        if (StringUtils.hasText(responseContent)) {
            return WXCode2SessionResultDTO.formJson(responseContent);
        }
        return null;
    }

    public String getPhoneNumber(Integer appType, String phoneNumberCode) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken(appType);
        Map<String, Object> data = new HashMap<>();
//        data.put("access_token", getAccessToken());
        data.put("code", phoneNumberCode);
        String responseContent = HttpUtils.postData(url, null, JSON.toJSONString(data));
        WeiXinPhoneNumber weiXinPhoneNumber = WeiXinPhoneNumber.fromJson(responseContent);
        if (weiXinPhoneNumber != null && weiXinPhoneNumber.getPhone_info() != null) {
            return weiXinPhoneNumber.getPhone_info().getPhoneNumber();
        }
        return null;
    }

    public String getAccessToken(Integer appType) {
        initAppConfig(appType);

        Lock lock = new ReentrantLock();
        lock.lock();
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            Map<String, Object> data = new HashMap<>();
            data.put("appid", this.appId);
            data.put("secret", this.secret);
            data.put("grant_type", "client_credential");
            String responseContent = HttpUtils.get(url, null, data);
            if (StringUtils.hasText(responseContent)) {
                WeiXinAccessTokenDTO dto = WeiXinAccessTokenDTO.formJson(responseContent);
                if (dto != null) {
                    return dto.getAccess_token();
                }
            }
        } catch (Exception e) {
            log.error("WeiXinService#getAccessToken", e);
        } finally {
            lock.unlock();
        }
        return null;
    }

//    public String getComponentAccessToken() {
//        try {
//            return wxOpenComponentService.getComponentAccessToken(false);
//        } catch (WxErrorException e) {
//            log.error("wxOpenComponentService#getComponentAccessToken", e);
//        }
//        return null;
//    }

    private void initAppConfig(Integer appType) {
        if (appType == 1) {
            this.appId = wistWeiXinProperties.getMiniappAppid();
            this.secret = wistWeiXinProperties.getMiniappSecret();
        } else if (appType == 2) {
            this.appId = wistWeiXinProperties.getExpressappAppid();
            this.secret = wistWeiXinProperties.getExpressappSecret();
        } else {
            log.error("appType: + " + appType + ", 无配置信息");
        }
    }

}
